package com.pig4cloud.pig.admin.api.util;

import com.alibaba.fastjson.JSONObject;
import com.pig4cloud.pig.admin.api.dto.loginDTO;
import lombok.experimental.UtilityClass;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Base64Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@UtilityClass
public class HttpTool {
	String url = "http://pig-register:9999";
	public Map<String, String> loginMap(loginDTO param) {
		Map<String, String> map = new HashMap<>();
		if(null == param.getUsername()){
			map.put("msg","请重新登入！");
			return map;
		}
		try {
			String loginmsg = sendPost(param);
			if(null != loginmsg){
				JSONObject jsonObject = JSONObject.parseObject(loginmsg);
				String msg = jsonObject.getString("msg");
				if(null != msg){
					String code = jsonObject.getString("code");
					String data = jsonObject.getString("data");
					map.put("code",code);
					map.put("msg",msg);
				}else {
					String access_token = jsonObject.getString("access_token");
					String user_info = jsonObject.getString("user_info");
					JSONObject info = JSONObject.parseObject(user_info);
					String id = jsonObject.getString("id");
					String username = jsonObject.getString("username");
					String phone = jsonObject.getString("phone");
					map.put("access_token",access_token);
					map.put("id",id);
					map.put("username",username);
					map.put("phone",phone);
					map.put("msg",null);
					sendGet(access_token);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public String sendPost(loginDTO param) {
		String requestUrl = "/auth/oauth2/token?grant_type=password&scope=server&username=" + param.getUsername()
				+ "&password=" + param.getPassword();
		if (param.getCode() != null && !"".equals(param.getCode())) {
			requestUrl = requestUrl + "&code" + param.getCode();
		}

		requestUrl = url + requestUrl;
		String params = "{}";
		InputStream inputStream = null;
		try {
			HttpClient httpClient = new HttpClient();
			PostMethod postMethod = new PostMethod(requestUrl);
			// 设置请求头 Content-Type
			postMethod.setRequestHeader("Content-Type", "application/json");
			// Base64加密方式认证方式下的basic auth
			postMethod.setRequestHeader("Authorization", "Basic cGlnOnBpZw==");
			RequestEntity requestEntity = new StringRequestEntity(params, "application/json", "UTF-8");
			postMethod.setRequestEntity(requestEntity);
			httpClient.executeMethod(postMethod);// 执行请求
			inputStream = postMethod.getResponseBodyAsStream();// 获取返回的流
			BufferedReader br = null;
			StringBuffer buffer = new StringBuffer();
			// 将返回的输入流转换成字符串
			br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
			}
			System.out.println("接口返回内容为:" + buffer);
			return buffer.toString();
		}
		catch (Exception e) {
			System.out.println("请求异常" + e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
		finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void sendGet(String token) throws IOException {
		//http://localhost:8080/api/auth/token/check_token?token=b38659e5-1ccc-4ffb-95b6-47666233c8ab
		String requestUrl ="/auth/token/check_token?token="+token;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//构造httpGet请求对象
		HttpGet httpGet = new HttpGet(url + requestUrl);

		httpGet.addHeader("Content-Type", "application/json");
		httpGet.addHeader("Authorization","Basic cGlnOnBpZw==");

		//可关闭的响应,用于获取响应回来的数据
		CloseableHttpResponse response = null;
		try {
			//httpclient客户端执行需要请求的对象,捕获异常
			response = httpClient.execute(httpGet);
			//响应的结果
			HttpEntity entity = response.getEntity();
			//EntityUtils是对Entity进行操作的工具类
			String resultStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);

			System.out.println(resultStr);
			//确保释放资源,释放流
			EntityUtils.consume(entity);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			httpClient.close();
			response.close();
		}
	}
	public static void main(String[] arg) throws IOException {
		//sendGet("691b6b23-24dd-4e3c-84ee-2f661aad168b");

		String str = new String(Base64.getEncoder().encode(("admin:123456").getBytes()),"UTF-8");
		System.out.println(str);
	}
}
